﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.esriSystem;

namespace EAGL.Core
{
    /// <summary>
    /// Basic serialization utility class that uses the XMLSerializer to do its work
    /// </summary>
    public class TXMLSerializer
    {
        public byte[] Serialize(object o)
        {
            string url = "http://www.esri.com/schemas/ArcGIS/9.0";
            IXMLStream stream = new XMLStreamClass();
            IXMLWriter writer = new XMLWriterClass();
            writer.WriteTo(stream as IStream);
            IXMLSerializer serializer = new XMLSerializerClass();
            serializer.WriteObject(writer, null, null, "", url, o);
            return stream.SaveToBytes();
        }

        public object Deserialize(byte[] bytes)
        {
            IXMLStream stream = new XMLStreamClass();
            stream.LoadFromBytes(ref bytes);
            IXMLReader reader = new XMLReaderClass();
            reader.ReadFrom(stream as IStream);
            IXMLSerializer serializer = new XMLSerializerClass();
            object obj = serializer.ReadObject(reader, null, null);
            IPersistStream pstream = obj as IPersistStream;
            return pstream;
        }

        public void SaveToFile(object o, string fileName)
        {
            string url = "http://www.esri.com/schemas/ArcGIS/9.0";
            IXMLStream stream = new XMLStreamClass();
            IXMLWriter writer = new XMLWriterClass();
            writer.WriteTo(stream as IStream);
            IXMLSerializer serializer = new XMLSerializerClass();
            serializer.WriteObject(writer, null, null, "", url, o);
            stream.SaveToFile(fileName);
        }

        public object LoadFromFile(string fileName)
        {
            IXMLStream stream = new XMLStreamClass();
            stream.LoadFromFile(fileName);
            IXMLReader reader = new XMLReaderClass();
            reader.ReadFrom(stream as IStream);
            IXMLSerializer serializer = new XMLSerializerClass();
            object obj = serializer.ReadObject(reader, null, null);
            IPersistStream pstream = obj as IPersistStream;
            return pstream;
        }
    }
}
